<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom: 5px">
      一级分类：
      <el-select v-model="listQuery.pId" filterable placeholder="请选择">
        <el-option
            v-for="item in catOneList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>


      <el-input v-model="listQuery.name" placeholder="分类名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
            :key="tableKey"
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width: 100% "
            @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="分类名" width="150px">
        <template slot-scope="{row}">
          <span style="color: cornflowerblue" class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="父类id" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.pId }}</span>
        </template>
      </el-table-column>


      <el-table-column label="图片" width="150px" align="center">
        <template slot-scope="{row}">
          <img style="width:100px" :src="row.picUrl" alt="">
        </template>
      </el-table-column>


      <el-table-column label="排序" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.order }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>

      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="一级分类" prop="pId">
          <template>
            <el-select v-model="temp.pId" filterable placeholder="留空是一级分类">
              <el-option
                  v-for="item in catOneList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="分类名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="品牌分类对应的图片">
          <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handlePicSuccess"
                  :before-upload="beforeIconDUpload">
            <img v-if="temp.picUrl" :src="temp.picUrl" class="avatar">
            <i v-else  class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="排序" prop="order">
          <el-input x-placement="大的在前" v-model="temp.order" type="number" />
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  // import { catList, catCreate, catDel, list, create, del } from '@/api/poster'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import { parseTime } from '@/utils'


  export default {
    name: 'ComplexTable',
    components: { Pagination },
    filters: {
      parseTime
    },
    data() {
      return {
        uploadUrl: '/admin/user/uploadPic?hasThumb=0',
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        catOneList: null,
        listQuery: {
          pId: 0,
          pageNum: 1,
          pageSize: 20,
          name: undefined,
          sort: '+id',
          ifList:1
        },
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        showReviewer: false,
        temp: {
          id: undefined,
          pId: undefined,
          name: undefined,
          picUrl: undefined,
          order: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '更新',
          create: '创建'
        },
        dialogPvVisible: false,
        rules: {
          name: [{ required: true, message: 'title is required', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.getList()
      this.getCateOneList()
    },
    methods: {
      //获取一级分类的列表
      getCateOneList(){
        const data = {}
        data.pId = 0;
        catList(data).then(response => {
          this.catOneList = response.data.items
          this.catOneList.unshift({'id':0,'name':'无一级分类'})
        })
      },
      getList() {
        this.listLoading = true
        catList(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total

          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.pageNum = 1
        this.getList()
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          pId: 0,
          name: undefined,
          picUrl: undefined,
          order: undefined,
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            catCreate (this.temp).then(response => {
              this.temp.id = response.id
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            catCreate (tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) {
        catDel(row).then(() => {
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
          this.total -= 1
        })




      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      handlePicSuccess(res, file) {
        if(res.code == 0){
          this.$message.success('上传成功');
          this.temp.picUrl = process.env.VUE_APP_BASE_API+'storage/images/'+res.data.picUrl;
          this.$data.temp = Object.assign({}, this.$data.temp);
        }else{
          this.$message.error(res.message);
        }
      },
      beforeIconDUpload(file) {
        const isJPG = file.type === 'image/jpeg'||file.type === 'image/png'||file.type === 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 20;

        if (!isJPG) {
          this.$message.error('上传图片的格式不正确');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    display: block;
  }
</style>
